<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">状态：{{ data.form.docStatus }}</h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()" value="1"> 返 回</a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)">
                保 存
              </a-button>
              <a-button @click="edit()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)">
                编 辑
              </a-button>
              <a-button @click="del()" v-if="!(data.form.edit || data.form.docStatus === 'L')" value="5"> 删 除</a-button>
              <a-dropdown arrow v-if="!(data.form.edit || data.form.docStatus === 'L')">
                <a-button>更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" :disabled="!(data.form.docStatus !== 'C')">关闭</a-menu-item>
                    <a-menu-item key="b" :disabled="!(data.form.docStatus === 'C')">打开</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="题型" name="quesTypeId">
              <a-select v-if="data.form.edit" v-model:value="data.form.quesTypeId" @change="change">
                <a-select-option :value="1" key="单选题">单选题</a-select-option>
                <a-select-option :value="2" key="多选题">多选题</a-select-option>
                <a-select-option :value="3" key="判断题">判断题</a-select-option>
                <a-select-option :value="4" key="定型填空题">定型填空题</a-select-option>
              </a-select>
              <span v-else>{{ data.form.quesTypeName }}</span>
            </a-form-item>

            <a-form-item label="题干" name="question">
              <a-textarea :rows="6" v-if="data.form.edit" v-model:value="data.form.question" />
              <span v-else>{{ data.form.question }}</span>
            </a-form-item>
            <a-form-item label="难度" name="difficulty">
              <a-rate :disabled="!data.form.edit" v-model:value="data.form.difficulty" />
            </a-form-item>

            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8"></a-col>
        </a-row>
      </a-form>
      <a-row>
        <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
          <a-tab-pane key="1" tab="明细">
            <a-button-group v-if="data.form.edit">
              <a-button @click="lineaAdd" type="link"> 插入行</a-button>
            </a-button-group>

            <a-table
              row-key="lineNum"
              :header-height="32"
              :columns="columnsb"
              :data-source="data.form.lista"
              :scroll="{ y: 450, x: 1500 }"
              :pagination="{
                showSizeChanger: true,
                showQuickJumper: true,
                defaultPageSize: 20,
                pageSizeOptions: ['20', '50', '100', '200'],
              }"
            >
              <template #bodyCell="{ text, record, column }">
                <template v-if="record.edit && column.dataIndex === 'answer'">
                  <a-input v-model:value="record.answer" />
                </template>
                <template v-if="column.dataIndex === 'inspect'">
                  <a-checkbox v-if="record.edit" v-model:checked="record.inspect"></a-checkbox>
                  <span v-else>
                    {{ record.inspect ? '是' : '否' }}
                  </span>
                </template>
                <template v-if="record.edit && column.dataIndex === 'freeTxt'">
                  <a-input v-model:value="record.freeTxt" />
                </template>
                <template v-if="data.form.edit && column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button
                      :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                      v-if="record.lineNum === data.form.lista.length"
                      @click="lineaDel(record)"
                      type="link"
                      danger
                    >
                      <template #icon>
                        <DeleteOutlined />
                      </template>
                    </a-button>
                  </a-button-group>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-card>
  </a-spin>
  <userList v-if="data.visible.user" :visible="data.visible.user" :onClose="onLinebColse"></userList>
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { smartSentry } from '/src/lib/smart-sentry';
  import { questionsApi } from '/src/api/business/exam/questions-api.js';

  import { useRouter, useRoute } from 'vue-router';
  import { columnsb } from '/src/views/business/exam/questionData/data.js';
  import userList from '/src/components/business/exam/userList.vue';

  const route = useRoute();
  const router = useRouter();

  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',
      absId: '',
      approved: false,
      docStatus: 'O',
      edit: false,
      lista: [],
      listb: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
      user: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
    activeKey: '1',
  });

  const tableLoading = ref(false);
  const formRef = ref(null);

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  // 更多操作
  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      questionsApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      questionsApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    }
  }

  // 增删改查
  function add() {
    data.form.objId = 78;
    data.form.objName = '日历';
    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/erp/questiona', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          questionsApi
            .update(data.form)
            .then((res) => {
              queryData(data.form.docEntry);
              message.success('修改成功！');
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        } else {
          questionsApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/erp/questiona', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        questionsApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/exam/question' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  async function queryData() {
    tableLoading.value = true;
    formRef.value.resetFields();
    try {
      let queryResult = await questionsApi.info(data.form.docEntry);
      data.form = queryResult.data;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;

      message.success('查询成功！');
    }
  }

  function refresh() {
    queryData();
  }

  function back() {
    router.push({ path: '/exam/question' });
  }

  function change(item, { key }) {
    data.form.quesTypeName = key;
  }

  // 行-----------------------------------------------------------------------------------------------------

  function lineaAdd() {
    data.form.lista.push({
      docEntry: data.form.docEntry,
      lineNum: data.form.lista.length + 1,
      lineStatus: 'O',
      nowDate: null,
      workDay: false,
      week: '',
      festName: '',
      multiple: 1,
      edit: true,
    });
  }

  function lineaDel(item) {
    data.form.lista.splice(item.lineNum - 1, 1);
  }

  //--------------------------------------------b-------------------------------------------

  function onLinebColse(item) {
    data.visible.user = false;
  }

  onMounted(init);
</script>
